const Router = require('../../Router');
const resContent = require('../../../../util/ResValue');
const Http = require('../../../../util/Http');
const SqlWhere = require('../../../../util/SqlWhere');
const dbUtil = require('../../../../util/dbutil');
const Where = require("../../../../util/SqlWhere");

class CityWeather extends Router {
    constructor() {
        super('/cityWeather', 'get', true);
    }


    async handle(ctx, next) {
        const body = ctx.request.query;
        if (body.id) {
            //通过城市id查询城市
            const whereNew = await dbUtil.getRow(`
            SELECT JSON_OBJECT(
                    'id', city.id,
                    'name', city.name,
                    'fatherId', city.fatherId,
                    'level', city.level,
                    'code', city.code
                ) AS city, weather.*
                FROM city
                JOIN weather ON city.id = weather.cityId WHERE city.id = ?`, [body.id]);
            // 1714
            if (!whereNew) {
                ctx.body = {
                    code: 234,
                    message: '消失的天气数据.'
                }
                return 0;
            }
            ctx = await resContent.success(ctx);
            whereNew.day7Info = JSON.parse(whereNew.day7Info);
            whereNew.city = JSON.parse(whereNew.city);
            ctx.body.data = whereNew;
            return 0;
        }
        const city = await this.getUserCity(ctx);
        if ((!city.country || city.country === '') && !body.name) {
            ctx = await resContent.theCityQueryFailed(ctx);
            ctx.body.data = city;
            return 0;
        }
        if (!body.name) {
            //设置城市信息
            body.name = city.city;
        }
        const weather = await dbUtil.getRow(`
            SELECT JSON_OBJECT(
                    'id', city.id,
                    'name', city.name,
                    'fatherId', city.fatherId,
                    'level', city.level,
                    'code', city.code
                ) AS city, weather.*
                FROM city
                JOIN weather ON city.id = weather.cityId WHERE city.name = ?`, [city.city]);
        ctx = await resContent.success(ctx);

        weather.day7Info = JSON.parse(weather.day7Info);
        weather.city = JSON.parse(weather.city);
        ctx.body.data = weather;
    }

    //获取用户当前城市
    async getUserCity(ctx) {
        //获取客户端ipv4地址
        const ip = ctx.request.headers['x-forwarded-for'] || ctx.request.socket.remoteAddress;
        const ipv4 = ip.replace(/^.*:/, ''); // 提取 IPv4 地址
        return await Http.obtainTheIPLocation(ipv4);
    }
}


module.exports = CityWeather;
